import * as step from '@flow-step/step-toolkit'
import fs from 'fs'
import path from 'path'

export function resolveVersion(workSpace: string, versionType: string | undefined, inputVersion: string | undefined): string {
    if (versionType == undefined) {
        let errMsg = 'missing version type'
        throw new Error(errMsg)
    }
    const versionFilePath = path.join(workSpace, '.nvmrc')
    let version = getNodeVersionFromFile(versionFilePath)
    if (versionType === 'NVMRC' && !version) {
        let errMsg = `Get node version from .nvmrc but could not determine node version from ${versionFilePath}.`
        throw new Error(errMsg)
    }
    if (version) {
        return version
    }
    if (inputVersion === undefined) {
        let errMsg = 'missing input version'
        throw new Error(errMsg)
    } else {
        return inputVersion
    }
}

export function getNodeVersionFromFile(versionFilePath: string): string | null {
    if (!fs.existsSync(versionFilePath)) {
        step.info(`The specified node version file at: ${versionFilePath} does not exist`)
        return null
    }

    const content = fs.readFileSync(versionFilePath, 'utf8')
    return content.trim()
}